package com.daervin.svc.common.utils;

import java.net.*;
import java.util.Enumeration;

/**
 * Created by daervin on 2023/8/22
 */
public class SystemUtil {

    public static void main(String[] args) throws Exception {
        InetAddress addr = InetAddress.getLocalHost();
        // 如果是回环网卡地址, 则获取ipv4 地址
        if (addr.isLoopbackAddress()) {
            addr = getInet4Address();
        }

        System.out.println("Local HostAddress: " + addr.getHostAddress());
        String hostname = addr.getHostName();
        System.out.println("Local host name: " + hostname);
        System.out.println("ip 地址:" + addr.getHostAddress() + ", 是否是回环网卡: " + addr.isLoopbackAddress());

    }

    /**
     * 获取IPV4网络配置
     */
    private static InetAddress getInet4Address() throws SocketException {
        // 获取所有网卡信息
        Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
        while (networkInterfaces.hasMoreElements()) {
            NetworkInterface netInterface = (NetworkInterface) networkInterfaces.nextElement();
            Enumeration<InetAddress> addresses = netInterface.getInetAddresses();
            while (addresses.hasMoreElements()) {
                InetAddress ip = (InetAddress) addresses.nextElement();
                if (ip instanceof Inet4Address) {
                    return ip;
                }
            }
        }
        return null;
    }
}
